import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/common/tree_node_bean.dart';
import 'package:enterprise_v6_app/app/data/common/tree_node_child_bean.dart';
import 'package:get/get.dart';

class OrganizePeopleTreeController<T1 extends TreeNodeBean, T2 extends TreeNodeChildBean> extends GetxController {

  /// 查询组织接口
  String? organizeInterface;

  /// 查询人员接口
  String? peopleInterface;

  /// 组织数据
  List<T1> departmentTreeList = [];

  /// 树节点组织请求参数
  Map<String, dynamic>? queryParameters;

  /// 子节点请求参数名
  String? nodeParameterName;

  /// 初始化
  Future<void> init({
    String? associationId,
    String? organizeInterface,
    String? peopleInterface,
    Map<String, dynamic>? queryParameters,
    String? nodeParameterName,
  }) async {
    this.organizeInterface = organizeInterface;
    this.peopleInterface = peopleInterface;
    this.queryParameters = queryParameters;
    this.nodeParameterName = nodeParameterName;
    // 初始化数据
    initData();
  }

  /// 初始化组织数据
  Future<void> initData() async {
    //获取所有组织数据
    final res = await HttpUtil()
        .generateGetRequest<List<T1>>(
          organizeInterface ?? Interface.getEmergencyPlansTree,
          queryParameters: queryParameters,
        )
        .execute();
    res.onSuccess((result) {
      if (result.data != null) {
        departmentTreeList = result.data!;
      }
      update();
    });
  }

  /// 点击组织节点
  Future<void> clickOnNode(T1 treeEntity) async {
    treeEntity.isExpand = !treeEntity.isExpand;
    // 展开状态且节点人员为空调用接口查询人员
    if (treeEntity.isExpand && treeEntity.userList.isEmpty) {
      final userList = await getUserByTypeAndBDepart(treeEntity);
      treeEntity.userList.addAll(userList);
      update();
    } else {
      update();
    }
  }

  /// 获取组织人员
  Future<List<T2>> getUserByTypeAndBDepart(T1 treeEntity) async {
    final List<T2> userList = [];
    //获取组织人员数据
    final res = await HttpUtil().generateGetRequest<List<T2>>(
      peopleInterface ?? Interface.getOrganizationRoleList,
      queryParameters: {
        '$nodeParameterName': treeEntity.getId(),
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        userList.addAll(result.data!);
      }
    });
    return userList;
  }
}
